package com.zjeav.lingjiao.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonSyntaxException;
import com.jpeng.jptabbar.JPTabBar;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.adapter.FindAdapter;
import com.zjeav.lingjiao.base.baseBean.Extra;
import com.zjeav.lingjiao.base.baseBean.Find;
import com.zjeav.lingjiao.base.baseBean.Result;
import com.zjeav.lingjiao.base.request.FindRequset;
import com.zjeav.lingjiao.base.utils.StringUtils;
import com.zjeav.lingjiao.base.utils.UIUtils;
import com.zjeav.lingjiao.ui.book.SaoMiaoBookActivity;
import com.zjeav.lingjiao.ui.home.Find.FindActivity;
import com.zjeav.lingjiao.ui.home.Find.FindwebViewActivity;
import com.zjeav.lingjiao.ui.home.persenter.FindDetailPersenter;
import com.zjeav.lingjiao.ui.home.persenter.MainPersenter;
import com.zjeav.lingjiao.ui.home.view.FindContract;
import com.zjeav.lingjiao.ui.home.view.FindDetailContract;

import java.util.ArrayList;

import static android.app.Activity.RESULT_OK;

/**
 * Created by jpeng on 16-11-14.
 */
public class FindFragment extends Fragment implements FindContract.View,View.OnClickListener,
        FindDetailContract.View{
    JPTabBar mTabBar;
    RecyclerView recyclerView;
    RefreshLayout refreshLayout;
    int index,size=10;
    ImageView saomiao_img;
    MainPersenter mainPersenter;
    private int REQUEST_CODE_SCAN = 111;
    FindAdapter adapter;
    FindDetailPersenter findDetailPersenter;
    ArrayList<Find> finds=new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.find,null);
        init(layout);
        return layout;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            index = 1;
                            refreshLayout.finishRefresh();
                        } catch (JsonSyntaxException e) {
                            UIUtils.showToast("数据加载异常");
                            e.printStackTrace();
                        }
                    }
                }, 2000);
            }
        });
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                index++;
                mainPersenter.getFinds(new FindRequset(index, size,""));
                refreshlayout.finishLoadmoreWithNoMoreData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            index = 1;
                            finds.clear();
                            adapter.replaceData(finds);
                            mainPersenter.getFinds(new FindRequset(index, size,""));
                            refreshLayout.finishRefresh();
                        } catch (JsonSyntaxException e) {
                            UIUtils.showToast("数据加载异常");
                            e.printStackTrace();
                        }
                    }
                }, 2000);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        finds.clear();
        index = 1;
        mainPersenter.getFinds(new FindRequset(index, size,""));
    }


    /**
     * 初始化
     */
    private void init(View layout) {
        mTabBar = ((RestructureMainActivity)getActivity()).getTabbar();
        recyclerView = layout.findViewById(R.id.recyclerView);
        refreshLayout = layout.findViewById(R.id.refreshLayout);
        saomiao_img = layout.findViewById(R.id.saomiao_img);
        saomiao_img.setOnClickListener(this);

        findDetailPersenter = new FindDetailPersenter(this);
        adapter = new FindAdapter(getContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
        mainPersenter = new MainPersenter(this);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Find find = (Find) adapter.getItem(position);
                findDetailPersenter.getdind(find.getId());

            }
        });

    }

    @Override
    public void showFinds(Extra extra, ArrayList<Find> books) {
        this.finds.addAll(books);
        adapter.replaceData(this.finds);
    }

    @Override
    public void ShowError(Throwable throwable) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.saomiao_img:
                saoMiao();
                break;
            default:
                break;
        }
    }

    private void saoMiao() {
        Intent intent = new Intent(getActivity(), CaptureActivity.class);

        /*ZxingConfig是配置类
         *可以设置是否显示底部布局，闪光灯，相册，
         * 是否播放提示音  震动
         * 设置扫描框颜色等
         * 也可以不传这个参数
         * */
        ZxingConfig config = new ZxingConfig();
        config.setPlayBeep(true);//是否播放扫描声音 默认为true
        config.setShake(true);//是否震动  默认为true
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                Intent intent = new Intent(getContext(), SaoMiaoBookActivity.class);
                intent.putExtra("content", content);
                startActivity(intent);
            }
        }
    }

    @Override
    public void showGetFind(Result<Find> find) {
        String strurl = find.getData().getH5url();
        if (!StringUtils.isNullOrEmpty(strurl)){
            Intent intent = new Intent(getContext(), FindwebViewActivity.class);
            intent.putExtra("url", strurl);
            startActivity(intent);
        }

    }

    @Override
    public void showError(Throwable throwable) {

    }
}
